package com.niiwoo.civet.trade.service.local.cardniu;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;

import com.niiwoo.civet.trade.dao.entity.*;
import com.niiwoo.civet.trade.dto.response.myloan.GetWithholdRepaymentResultDTO;
import com.niiwoo.civet.trade.service.local.newRefund.common.RefundLocalService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.common.collect.Sets;
import com.niiwoo.civet.account.dto.common.BankCardDTO;
import com.niiwoo.civet.account.service.bankcard.BankCardDubboService;
import com.niiwoo.civet.base.enums.FeeTypeEnum;
import com.niiwoo.civet.base.enums.OrderTradeSourceEnum;
import com.niiwoo.civet.base.enums.RefundOrderStatusEnum;
import com.niiwoo.civet.base.enums.RefundTypeEnum;
import com.niiwoo.civet.trade.dao.mapper.*;
import com.niiwoo.civet.trade.dto.ProjectBorrowerPlanNewDTO;
import com.niiwoo.civet.trade.dto.ProjectRepayTotalAmountDTO;
import com.niiwoo.civet.trade.dto.RefundOrderTradeSourcePeriodDTO;
import com.niiwoo.civet.trade.dto.response.cardniu.CardNiuLoanCreditAmountDTO;
import com.niiwoo.civet.trade.dto.response.cardniu.RepayPlanInfo;
import com.niiwoo.civet.trade.dto.response.cardniu.RepayResultDTO;
import com.niiwoo.civet.trade.enums.BorrowerPlanRefundStatusEnum;
import com.niiwoo.civet.trade.enums.CardNiuRefundStatusEnum;
import com.niiwoo.civet.trade.service.cardniu.CardNiuLoanDubboService;
import com.niiwoo.civet.trade.service.local.newRefund.common.RefundCommonService;
import com.niiwoo.civet.trade.service.local.refund.CommonLocalService;
import com.niiwoo.civet.trade.utils.RepaymentUtil;
import com.niiwoo.civet.user.service.UserCreditDubboService;
import com.niiwoo.tripod.provider.exception.BizException;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by yuanguang on 2018/2/10.
 */
@Service
@Slf4j
public class CardNiuRefundLocalService {
	
    @Autowired
    private ProjectMapperExt projectMapper;
    
    @Autowired
    private ProjectBorrowerSummaryMapperExt projectBorrowerSummaryMapper;
    
    @Autowired
    private ProjectBorrowerPlanNewMapperExt projectBorrowerPlanNewMapper;
    
    @Autowired
    private ProjectBorrowerPlanDetailMapperExt projectBorrowerPlanDetailMapper;
    
    @Autowired
    private RefundOrderMapperExt refundOrderMapperExt;

    @Autowired
    private RefundOrderDetailMapperExt refundOrderDetailMapper;
    
	@Autowired
	private RefundWithholdOrderMapperExt refundWithholdOrderMapperExt;
    
    @Autowired
    private CardNiuLoanLocalService cardNiuLoanLocalService;

    @Autowired
    private CardNiuLoanDubboService cardNiuLoanDubboService;
    
    @Autowired
    private CommonLocalService commonLocalService;
    
    @Autowired
    private RefundCommonService refundCommonService;

    @Reference(version = "1.0.0")
    private UserCreditDubboService userCreditDubboService;
    
    @Reference(version = "1.0.0")
    private BankCardDubboService bankCardDubboService;
    @Autowired
    private RefundLocalService refundLocalService;
    
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    
    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


	@Transactional
    public RepayResultDTO queryRepayResult(Long projectId, String orgRequestNo,Long refundOrderId){
        RepayResultDTO repayResultDTO = new RepayResultDTO();
		Assert.notNull(projectId, "请求参数projectId不能为空");

        // 还款订单
        RefundOrder refundOrder = null;
        if(!StringUtils.isEmpty(orgRequestNo)){
			GetWithholdRepaymentResultDTO resultDTO = refundLocalService.getWithholdRepaymentResult(projectId,orgRequestNo);
			repayResultDTO.setRepayTime(sdf.format(new Date()));
			if(resultDTO==null){
				repayResultDTO.setRepayStatus(2);
				repayResultDTO.setFailMessage("查询无此请求流水号");
			}else{
				repayResultDTO.setFailCode(resultDTO.getErrorCode());
				repayResultDTO.setFailMessage(resultDTO.getErrorMessage());
				if(RefundOrderStatusEnum.HANDLED.getCode().equals(resultDTO.getStatus())){
					repayResultDTO.setRepayStatus(1);
				}else if(RefundOrderStatusEnum.HANDLEFAIL.getCode().equals(resultDTO.getStatus())){
					repayResultDTO.setRepayStatus(2);
				}else{
					repayResultDTO.setRepayStatus(3);
				}
			}
			refundOrder = refundOrderMapperExt.selectByProjectIdAndOrgRequestNo(projectId,orgRequestNo);
		}else{
			refundOrder = refundOrderMapperExt.selectByPrimaryKey(refundOrderId);
		}

		if(refundOrder!=null){
			Set<Integer> periods = Sets.newLinkedHashSet(); // 记录本次还款期数
			// 本次还款金额详情（累计本次还款金额）
			List<RefundOrderDetailBiz> refundOrderDetailBizList = refundCommonService.getNotRefundOrderDetailBizByRefundOrderId(refundOrder.getId());
			refundOrderDetailBizList.forEach(refundOrderDetailBiz -> {
				periods.add(refundOrderDetailBiz.getCurrentPeriod());

				repayResultDTO.setRepayPrincipal(repayResultDTO.getRepayPrincipal().add(refundOrderDetailBiz.getCapital()));
				repayResultDTO.setRepayInterest(repayResultDTO.getRepayInterest().add(refundOrderDetailBiz.getInterest()));
				repayResultDTO.setRepayServiceInterest(repayResultDTO.getRepayServiceInterest().add(refundOrderDetailBiz.getManageFee()));
				repayResultDTO.setRepayPenaltyInterest(repayResultDTO.getRepayPenaltyInterest().add(refundOrderDetailBiz.getPenaltyFee()));
				repayResultDTO.setGuaranteeFee(repayResultDTO.getGuaranteeFee().add(refundOrderDetailBiz.getGuaranteeFee()));
				repayResultDTO.setRepayTotal(refundOrderDetailBiz.getAmount());
			});
			// 还款支付方式
			if (OrderTradeSourceEnum.BALANCE_FULL_JOB.getTradeSource().equals(refundOrder.getTradeSource())
					|| OrderTradeSourceEnum.BALANCE_PARTIAL_JOB.getTradeSource().equals(refundOrder.getTradeSource())
					|| OrderTradeSourceEnum.WITHHOLD.getTradeSource().equals(refundOrder.getTradeSource())
					|| OrderTradeSourceEnum.AEGIS.getTradeSource().equals(refundOrder.getTradeSource())) {
				repayResultDTO.setRepayWay(3); // 系统扣款
			} else if (OrderTradeSourceEnum.APP.getTradeSource().equals(refundOrder.getTradeSource())) {
				repayResultDTO.setRepayWay(2); // 主动还款
			} else {
				repayResultDTO.setRepayWay(1); // 未还款
			}

			// 还款状态  1：成功；2：失败；3：处理中；
			if(refundOrder.getProcessStatus()==2){
				if (RefundOrderStatusEnum.HANDLED.getCode().equals(refundOrder.getStatus())) {
					repayResultDTO.setRepayStatus(1);
				} else {
					repayResultDTO.setRepayStatus(2);
				}
			}else{
				repayResultDTO.setRepayStatus(3);
			}

			repayResultDTO.setPeriods(StringUtils.join(periods.toArray(), ","));
			repayResultDTO.setRepayTime(sdf.format(refundOrder.getUpdateTime()));
			repayResultDTO.setFailCode(refundOrder.getErrorCode());
			repayResultDTO.setFailMessage(refundOrder.getErrorMessage());
		}

		Integer refundedPeriod = 0; // 已还款期数
		BigDecimal totalAmount = BigDecimal.ZERO; // 借款总金额
		BigDecimal refundedTotalAmount = BigDecimal.ZERO; // 已还总金额

		// 查询所有还款计划
		List<ProjectBorrowerPlanNewDTO> projectBorrowerPlanNewDTOList = Optional.ofNullable(projectBorrowerPlanNewMapper.selectByProjectIdForAmount(projectId))
				.orElseThrow(() -> new BizException("TRD20005"));
		
		for (ProjectBorrowerPlanNewDTO projectBorrowerPlanNewDTO : projectBorrowerPlanNewDTOList) {
			if (!BorrowerPlanRefundStatusEnum.NON_REPAYMENT.getCode().equals(projectBorrowerPlanNewDTO.getStatus())) {
				refundedPeriod = projectBorrowerPlanNewDTO.getPeriod();
			}
			totalAmount = totalAmount.add(projectBorrowerPlanNewDTO.getCapital()).add(projectBorrowerPlanNewDTO.getInterest())
					.add(projectBorrowerPlanNewDTO.getPenaltyFee()).add(projectBorrowerPlanNewDTO.getManagementFee()).add(projectBorrowerPlanNewDTO.getGuaranteeFee());
			
			refundedTotalAmount = refundedTotalAmount.add(projectBorrowerPlanNewDTO.getRefundedCapital()).add(projectBorrowerPlanNewDTO.getRefundedInterest())
					.add(projectBorrowerPlanNewDTO.getRefundedPenaltyFee()).add(projectBorrowerPlanNewDTO.getRefundedManagementFee())
					.add(projectBorrowerPlanNewDTO.getRefundedGuaranteeFee());
		}

		repayResultDTO.setPaidAmount(refundedTotalAmount);
		repayResultDTO.setTotalAmount(totalAmount.subtract(refundedTotalAmount));
		repayResultDTO.setFinishPeriod(refundedPeriod);

		// 标的还款摘要信息
        ProjectBorrowerSummary summary = Optional.ofNullable(projectBorrowerSummaryMapper.selectByPrimaryKey(projectId))
                .orElseThrow(() -> new BizException("TRD20010"));
		repayResultDTO.setTotalPeriod(summary.getTotalPeriod());
        repayResultDTO.setRepayPlanVersionTime(sdf.format(summary.getUpdateTime()));        

		// 还款计划详情
        List<RepayPlanInfo> repayPlanInfos = queryRepayPlanInfo(projectBorrowerPlanNewDTOList, summary);
        repayResultDTO.setRepayPlanInfo(repayPlanInfos);		

		// 银行卡信息
		BankCardDTO bankCardDTO = null;
		try {
			bankCardDTO = bankCardDubboService.getUserBankCardInfo(summary.getBorrowerUserId());
		} catch (Exception e) {
			log.error("bankCardDubboService.getUserBankCardInfo异常,error={}", e);
		}
		repayResultDTO.setBankCard(bankCardDTO == null ? "" : bankCardDTO.getBankAccountNo());
		
		// 用户极速借可用额度
		try {
	        CardNiuLoanCreditAmountDTO cardNiuLoanCreditAmount = cardNiuLoanDubboService.getCardNiuLoanCreditAmount(summary.getBorrowerUserId());
	        BigDecimal creditLimitAvailable = cardNiuLoanCreditAmount.getCreditTotalAmount().subtract(cardNiuLoanCreditAmount.getCreditUsedAmount());
	        repayResultDTO.setCreditLimitAvailable(creditLimitAvailable);
		} catch (Exception e) {
			log.error("cardNiuLoanDubboService.getCardNiuLoanCreditAmount异常,error={}", e);
		}

        return repayResultDTO;
    }

	/**
	 * 获取还款计划
	 * @param projectBorrowerPlanNewDTOList
	 * @param summary
	 * @return
	 */
    @Transactional
	public List<RepayPlanInfo> queryRepayPlanInfo(List<ProjectBorrowerPlanNewDTO> projectBorrowerPlanNewDTOList, ProjectBorrowerSummary summary) {
		
        List<RepayPlanInfo> repayPlanInfoList = Lists.newArrayList();
        
        Date currentDate = commonLocalService.getCurrentDate();
        
        // 获取每一期对应的还款来源
        List<RefundOrderTradeSourcePeriodDTO> refundOrderTradeSourcePeriodDTOList = refundOrderDetailMapper.listRefundOrderDetailByProjectId(summary.getProjectId());
        
		projectBorrowerPlanNewDTOList.forEach(projectBorrowerPlanNewDTO -> {
            RepayPlanInfo repayPlanInfoDTO = new RepayPlanInfo();

            // 当前应还总金额
			BigDecimal currentPeriodTotalAmount = projectBorrowerPlanNewDTO.getCapital().add(projectBorrowerPlanNewDTO.getInterest())
					.add(projectBorrowerPlanNewDTO.getPenaltyFee()).add(projectBorrowerPlanNewDTO.getGuaranteeFee())
					.add(projectBorrowerPlanNewDTO.getManagementFee());

			// 当前已还总金额
			BigDecimal currentPeriodRefundedTotalAmount = projectBorrowerPlanNewDTO.getRefundedCapital().add(projectBorrowerPlanNewDTO.getRefundedInterest())
					.add(projectBorrowerPlanNewDTO.getRefundedPenaltyFee()).add(projectBorrowerPlanNewDTO.getRefundedGuaranteeFee())
					.add(projectBorrowerPlanNewDTO.getRefundedManagementFee());
			
            repayPlanInfoDTO.setPeriodPrincipal(projectBorrowerPlanNewDTO.getCapital());
            repayPlanInfoDTO.setPeriodInterest(projectBorrowerPlanNewDTO.getInterest());
            repayPlanInfoDTO.setPeriodServiceChargeInterest(projectBorrowerPlanNewDTO.getManagementFee());
            repayPlanInfoDTO.setPeriodPenaltyInterest(projectBorrowerPlanNewDTO.getPenaltyFee());
            repayPlanInfoDTO.setGuaranteeFee(projectBorrowerPlanNewDTO.getGuaranteeFee());
            
			repayPlanInfoDTO.setPeriodTotal(currentPeriodTotalAmount);
			repayPlanInfoDTO.setPeriodRepayedAmount(currentPeriodRefundedTotalAmount);            
            
            repayPlanInfoDTO.setTerm(projectBorrowerPlanNewDTO.getPeriod() + "");
            
            // 本期帐单状态对应还款计划还款状态
			if (!BorrowerPlanRefundStatusEnum.NON_REPAYMENT.getCode().equals(projectBorrowerPlanNewDTO.getStatus())) {
				repayPlanInfoDTO.setBillStatus(CardNiuRefundStatusEnum.FINISHED.getValue());
			} else if (RepaymentUtil.getOverdueDay(projectBorrowerPlanNewDTO.getRefundDate(), currentDate) > 0) {
				repayPlanInfoDTO.setBillStatus(CardNiuRefundStatusEnum.OVERDUE.getValue());
			} else {
				repayPlanInfoDTO.setBillStatus(CardNiuRefundStatusEnum.REPAYING.getValue());
			}
			
			// 当期逾期时间
			Integer overDueDays = 0;
			if (BorrowerPlanRefundStatusEnum.NON_REPAYMENT.getCode().equals(projectBorrowerPlanNewDTO.getStatus())) {
				overDueDays = RepaymentUtil.getOverdueDay(projectBorrowerPlanNewDTO.getRefundDate(), currentDate);
			} else {
				overDueDays = RepaymentUtil.getOverdueDay(projectBorrowerPlanNewDTO.getRefundDate(), projectBorrowerPlanNewDTO.getOverDate());
			}
			repayPlanInfoDTO.setPeriodDaysOverdue(overDueDays > 0 ? overDueDays : 0);			
			
			Date refundEndDate = new Date();
			try {
				refundEndDate = format.parse(getDateEnd(projectBorrowerPlanNewDTO.getRefundDate()));
			} catch (Exception e) {
				log.error("计息结束时间格式转换出错");
			}
            repayPlanInfoDTO.setEndInterestTime(sdf.format(refundEndDate)); // 计息结束时间
			repayPlanInfoDTO.setStartInterestTime(sdf.format(DateUtils.addDays(DateUtils.addMonths(projectBorrowerPlanNewDTO.getRefundDate(), -1), 1))); // 当期计息开始时间 yyyyMMddHHmmss 减1个月加1天
			repayPlanInfoDTO.setPeriodStartRepayTime(sdf.format(DateUtils.addDays(DateUtils.addMonths(projectBorrowerPlanNewDTO.getRefundDate(), -1), 1))); // 当期可以还款时间减1个月加1天
            repayPlanInfoDTO.setPeriodLastDueTime(sdf.format(refundEndDate)); // 当期最迟还款时间（精确到秒，超过即逾期） 还款日期 23:59:59
			repayPlanInfoDTO.setPenaltyStartTime(sdf.format(DateUtils.addDays(projectBorrowerPlanNewDTO.getRefundDate(), 1))); //罚息计算开始时间 yyyyMMddHHmmss 加1天 00:00:00

			// 还款支付方式,1-未还款；2-主动还款；3-系统扣款；4-支付宝转账；5银行转账或其他方式
			repayPlanInfoDTO.setRepayWay(1);
			
			// 根据每一期的还款来源宽判断是支付方式
			for (RefundOrderTradeSourcePeriodDTO refundOrderTradeSourcePeriodDTO : refundOrderTradeSourcePeriodDTOList) {
				if (projectBorrowerPlanNewDTO.getPeriod() == refundOrderTradeSourcePeriodDTO.getCurrentPeriod()) {
					if (OrderTradeSourceEnum.BALANCE_FULL_JOB.getTradeSource().equals(refundOrderTradeSourcePeriodDTO.getTradeSource())
							|| OrderTradeSourceEnum.BALANCE_PARTIAL_JOB.getTradeSource().equals(refundOrderTradeSourcePeriodDTO.getTradeSource())
							|| OrderTradeSourceEnum.WITHHOLD.getTradeSource().equals(refundOrderTradeSourcePeriodDTO.getTradeSource())
							|| OrderTradeSourceEnum.AEGIS.getTradeSource().equals(refundOrderTradeSourcePeriodDTO.getTradeSource())) {
						repayPlanInfoDTO.setRepayWay(3); // 系统扣款
					} else if (OrderTradeSourceEnum.APP.getTradeSource().equals(refundOrderTradeSourcePeriodDTO.getTradeSource())) {
						repayPlanInfoDTO.setRepayWay(2); // 主动还款
					}
				}
			}
            repayPlanInfoList.add(repayPlanInfoDTO);
        });
		
        return repayPlanInfoList;
    }

    /**
     * 卡牛还款失败调整返回数据
     * 根据标的ID查询还款信息
     * @param projectId
     * @return
     */
	@Transactional
    public RepayResultDTO queryRepayResultByProjectId(Long projectId){
        RepayResultDTO repayResultDTO = new RepayResultDTO();

        // 标的摘要信息
        ProjectBorrowerSummary summary = Optional.ofNullable(projectBorrowerSummaryMapper.selectByPrimaryKey(projectId)).orElseThrow(() -> new BizException("TRD20001"));
        
		// 查询所有还款计划
		List<ProjectBorrowerPlanNewDTO> projectBorrowerPlanNewDTOList = Optional.ofNullable(projectBorrowerPlanNewMapper.selectByProjectIdForAmount(projectId))
				.orElseThrow(() -> new BizException("TRD20005"));
		
		Integer refundedPeriod = 0;
		BigDecimal totalAmount = BigDecimal.ZERO;
		BigDecimal refundedTotalAmount = BigDecimal.ZERO;
		for (ProjectBorrowerPlanNewDTO projectBorrowerPlanNewDTO : projectBorrowerPlanNewDTOList) {
			if (!BorrowerPlanRefundStatusEnum.NON_REPAYMENT.getCode().equals(projectBorrowerPlanNewDTO.getStatus())) {
				refundedPeriod = projectBorrowerPlanNewDTO.getPeriod();
			}
			totalAmount = totalAmount.add(projectBorrowerPlanNewDTO.getCapital()).add(projectBorrowerPlanNewDTO.getInterest())
					.add(projectBorrowerPlanNewDTO.getPenaltyFee()).add(projectBorrowerPlanNewDTO.getManagementFee()).add(projectBorrowerPlanNewDTO.getGuaranteeFee());
			
			refundedTotalAmount = refundedTotalAmount.add(projectBorrowerPlanNewDTO.getRefundedCapital()).add(projectBorrowerPlanNewDTO.getRefundedInterest())
					.add(projectBorrowerPlanNewDTO.getRefundedPenaltyFee()).add(projectBorrowerPlanNewDTO.getRefundedManagementFee())
					.add(projectBorrowerPlanNewDTO.getRefundedGuaranteeFee());
		}		
        repayResultDTO.setPaidAmount(refundedTotalAmount);
		repayResultDTO.setTotalAmount(totalAmount.subtract(refundedTotalAmount));
		
		repayResultDTO.setPeriods(bulidRefundPeroidDesc(refundedPeriod));
		repayResultDTO.setRepayWay(1);
		repayResultDTO.setRepayStatus(2);
		repayResultDTO.setTotalPeriod(summary.getTotalPeriod());
		repayResultDTO.setFinishPeriod(refundedPeriod);
        repayResultDTO.setRepayTime(sdf.format(summary.getUpdateTime()));
        repayResultDTO.setRepayPlanVersionTime(sdf.format(summary.getUpdateTime()));
        
        // 还款计划详情
		List<RepayPlanInfo> repayPlanInfos = queryRepayPlanInfo(projectBorrowerPlanNewDTOList, summary);
		repayResultDTO.setRepayPlanInfo(repayPlanInfos);

		BankCardDTO bankCardDTO = null;
		try {
			bankCardDTO = bankCardDubboService.getUserBankCardInfo(summary.getBorrowerUserId());
		} catch (Exception e) {
			log.error("bankCardDubboService.getUserBankCardInfo异常,error={}", e);
		}
		repayResultDTO.setBankCard(bankCardDTO == null ? "" : bankCardDTO.getBankAccountNo());
		repayResultDTO.setCreditLimitAvailable(cardNiuLoanLocalService.getCardNiuUsedCredit(summary.getBorrowerUserId()));
        return repayResultDTO;
    }
	
    /**
     *
     * @Description 获取指定日期结束时间
     * @param today
     * @return
     * @return String
     * @throws
     *
     */
    public static String getDateEnd(Date today) {
        String todayFormat = new SimpleDateFormat("yyyy-MM-dd").format(today);
        return todayFormat + " 23:59:59";
    }
    /**
     * 查询标的待还总金额
     * 
     * @param projectId
     * @return
     */
    public BigDecimal queryShouldRepayAmount(Long projectId) {
        Project project = Optional.ofNullable(projectMapper.selectByPrimaryKey(projectId)).orElseThrow(() -> new BizException("TRD_200001"));
    	
		ProjectRepayTotalAmountDTO projectRepayTotalAmountDTO = refundCommonService.getProjectTotalNeedRepayAmount(projectId, project.getBorrowUserId());
        return projectRepayTotalAmountDTO.getTotalAmount();
    }

    /**
     * 查询用户未还期数
     * @param userId
     * @return
     */
    public List<Integer> queryShouldRepayPeriods(String userId) {
        return projectBorrowerPlanNewMapper.queryShouldRepayPeriods(userId);
    }

	/**
	 * 计算还款后剩余还款本金
	 * @param projectId
	 * @param currentPeriod
	 * @return
	 */
	public BigDecimal calculatePrincipalUnfinished(Long projectId, Integer currentPeriod) {
    	return projectBorrowerPlanDetailMapper.countUnfinishedAmountForFeeType(projectId, currentPeriod, FeeTypeEnum.CAPITAL.getValue());
    }
    
    /**
     * 转换卡牛还款类型到交易中心的还款类型
     * 
     * @return
     */
    public RefundTypeEnum transformTradeRefundType(Integer repayType) {
    	RefundTypeEnum refundTypeEnum = RefundTypeEnum.IMMEDIATELY;
    	if (null == repayType) return refundTypeEnum;
    	
    	if (repayType == 2) {
    		refundTypeEnum = RefundTypeEnum.OVERDEPT;
    	}
    	return refundTypeEnum;
    }
    
    /**
     * 构建已还款期数描述
     * 
     * @param peroid
     * @return
     */
    private static String bulidRefundPeroidDesc(Integer peroid) {
    	if (null == peroid || 0 == peroid) return "";
    	
    	StringBuilder stringBuilder = new StringBuilder("");
		for (int i = 1; i <= peroid; i++) {
			stringBuilder.append(Integer.toString(i)).append(",");
		}
		return stringBuilder.substring(0, stringBuilder.length() - 1);
    }
}